package top.jingles.tools.deploytool.entity;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;

import lombok.Data;

@Data
public class Task {
    // pom-file
    File mainFile;
    // other files
    Map<String, JarList> files;
    // state
    TaskState state;
    // retry times
    int retryTimes;

    public enum TaskState {
        TS_READY,
        TS_RUNNING,
        TS_FINISH,
        TS_FAILED
    }

    public Task(File pomFile) {
        mainFile = pomFile;
        files = new HashMap<>();
        state = TaskState.TS_READY;
        retryTimes = 0;
    }

    public void addFile(JarInfo info) {
        // 添加到文件列表中，按照classifier分类存一下，便于分类加到仓库
        String classifier = info.getClassifier();
        if (files.containsKey(classifier)) {
            files.get(classifier).addJar(info);
        } else {
            JarList list = new JarList();
            list.addJar(info);
            files.put(classifier, list);
        }
    }

    public String toJSONString() {
        StringBuilder sb = new StringBuilder();
        sb.append("{\"mainFile\": \"")
            .append(mainFile.getAbsolutePath())
            .append("\", \"files\": [");
        boolean first = true;
        for (Entry<String, JarList> entry : files.entrySet()) {
            if (!first) {
                sb.append(", ");
            }
            sb.append("\"").append(entry.getValue().toJSONString());
            first = false;
        }
        sb.append("], \"state\": ")
            .append(state)
            .append(", \"retryTimes\": ")
            .append(retryTimes)
            .append("}");
        return sb.toString();
    }
}
